/**
 * Project: topdt-jbpm
 * Copyright 2013  Top Digital Technology  Co. Ltd.
 * All right reserved.
 */
package com.topdt.jbpm.service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.thx.common.spring.BeanFactory;
import com.topdt.jbpm.dao.ApplicationDao;
import com.topdt.jbpm.dao.FieldDao;
import com.topdt.jbpm.dao.FormInstanceDao;
import com.topdt.jbpm.dao.WorkDao;
import com.topdt.jbpm.form.SysParamService;
import com.topdt.jbpm.form.query.Option;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Field;
import com.topdt.jbpm.model.FormInstance;
import com.topdt.jbpm.model.Work;

/**
 * 建立日期 : 2013-4-25 下午12:00:29<br>
 * 作者 : balance<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
@Service
public class FormInstanceManager {
	@Autowired
	private FormInstanceDao formInstanceDao;
	@Autowired
	private FieldDao fieldDao;
	@Autowired
	private WorkDao workDao;
	@Autowired
	private ApplicationDao appDao;
	public FormInstance getById(String workId) {
		return formInstanceDao.getById(workId);
	}
	
	public Map<String,String> getDataById(String workId) {
		FormInstance form =formInstanceDao.getById(workId);
		if(form==null)
			return null;
		String json;
		try {
			json = new String(form.getFormData(),"utf-8");
		} catch (UnsupportedEncodingException e) {
			json = new String(form.getFormData());
		}
		Map<String,String> result = (Map<String, String>) JSON.parse(json);
		Work work = workDao.get(workId);
		Application app = appDao.get(work.getAppId());
		return conver2RealValue(result,app.getForm().getFormId());
	}
	
	
	public Map<String,String> conver2RealValue(Map<String,String> map,String formId){
		Map<String,String> result = new HashMap<String,String>();
		Set<String> keys =map.keySet();
		SysParamService spService = (SysParamService) BeanFactory.getBean(SysParamService.class);
		for(String key:keys){
			Field field = fieldDao.getFieldByFieldNameAndFormId(key,formId);
			if(field!=null){
				if(field.getFieldType().equals("select")||field.getFieldType().equals("radio")||field.getFieldType().equals("checkbox")){
					Option option =spService.getOptionName(map.get(key), "more");
					result.put(key, option.getName());
				}else if(field.getFieldType().equals("tree")){
					Option option =spService.getOptionName(key, "tree");
					result.put(key, option.getName());
				}else{
					result.put(key, map.get(key));
				}
			}
			
		}
		
		return result;
	}
}
